package org.ytor.core.sysapi.role.repository;

import org.springframework.stereotype.Repository;
import org.ytor.core.sqlflow.BaseRepository;
import org.ytor.core.sqlflow.SQLHelper;
import org.ytor.core.sqlflow.builder.select.WhereStage;
import org.ytor.core.sysapi.permission.model.SysPermission;
import org.ytor.core.sysapi.role.model.SysRolePermission;
import org.ytor.core.sysapi.role.model.SysRole;

import java.util.List;

import static org.ytor.core.sqlflow.builder.BuilderWrapper.expr;

/**
 * created by   on 2025年4月13日 16:01:41
 * <br/>
 * SysRole表Mapper
 * <br/>
 */
public class SysRoleRepository extends BaseRepository<SysRole> {

    public List<SysPermission> listAllPermissionByRoleId(String roleId) {
        WhereStage subSelect = SQLHelper.select(SysRolePermission::getPermissionId).from(SysRolePermission.class).where(w -> w.eq(SysRolePermission::getRoleId, roleId));
        return SQLHelper.select().from(SysPermission.class)
                .where(w -> w.in(SysPermission::getId, subSelect))
                .orderByAsc(SysPermission::getSort)
                .list();
    }

    public List<SysRolePermission> listRolePermissions(String roleId) {
        WhereStage subSelect = SQLHelper.select(SysRolePermission::getRoleId, SysRolePermission::getPermissionId).from(SysRolePermission.class).where(w -> w.eq(SysRolePermission::getRoleId, roleId));
        return SQLHelper.select(SysPermission::getPid, SysPermission::getPermissionName, SysPermission::getPermissionCode, SysPermission::getPermissionType)
                .selectRaw("sp.id as permissionId", "srp.role_id")
                .from(SysPermission.class)
                .leftJoin(subSelect, "srp", on -> on.eq(SysRolePermission::getId, expr("srp.permissionId")))
                .list(SysRolePermission.class);
    }
}